var errorMSG=[];
	errorMSG[01]="Url ajax vacía";
var urlRedir=[];
    urlRedir[408]="/privalia/";

var CestaVipMain = new Class.create({
    initialize: function () {
	this.idClass=1;		//Class Identifier (for debuggin purposes)
	this.debug = false;	
	this.error=false;	//To handle errors
	this.timeout = 4;	//In seconds
	this.timeoutTimer = "";	//setInterval var
	this.showLoad = true;	//Show Loading Image
	this.loading = false;	//Current Status
	this.idLoadText = 'loading';
	this.loadingTarget ="";
	this.urlGetData = "";	//ajax URL
	this.ajaxData =  "";	//Response data
        this.ajaxStatus =  "";	//Response status
	this.build="";
	this.Data=[];
	this.numTargets=0;	//targets to build
	this.built = '';
        this.tpl = '';
	this.target='';
	this.v_txt =[];
    },
//GETTERS
    getTarget: function () {
        return this.target;
    },
    getBuilt: function () {
        return this.built;
    },
    getAjaxData: function () {
        return this.ajaxData;
    },
    getBuild: function (){
	return this.build;
    },
    getStatus: function () {
        return (this.ajaxStatus == "success");
    },
    getTxt: function(text) {
	return this.v_txt[text];
    },
//SETTERS
   setCssJson: function (style) {
        this.cssJson = style;
    },
    setTxt: function(text, translation) {
	this.v_txt[text] = translation;
    },
    setTpl: function (tpl) {
        this.tpl = tpl;
    },
    setBuilt: function (built) {
        this.built = built;
    },
    setBuild: function (page) {
        if (page === undefined) {
            page = 'generic';
        }
        this.build = page;
    },
    setUrlGetData: function (url) {
        if (url != '') {
            this.urlGetData = url;
	   
        }
    },
    setShowLoad: function (showLoad) {
        this.showLoad = showLoad;
    },
    setTarget: function (target) {
        this.target = target;
    },
    setAsJsoned: function (target) {
        if (target != "") {
            $(target).removeClassName(this.cssJson);
            $(target).addClassName(this.cssJsoned);
        }
    },
    addBuilt: function (dataJson) {
        this.built += this.tpl.evaluate(dataJson);
    },
    resetBuilt: function(){
	this.setTpl('');
	this.setBuilt('');
    },
    errorMessage:function(errorCode){

	console.log('errorMessage@'+errorMSG[errorCode]);

    },
    startTimeout: function () {
        if (this.timeout) {
            var seconds = this.timeout;
            this.timeoutTimer = window.setTimeout((function () {
              this.header(408);
            }).bind(this), seconds * 1000);
        }
    },
    stopTimeout: function () {
        if (this.timeout) {
            window.clearTimeout(this.timeoutTimer);
            if (this.debug) { console.log("CestaVipMain.stopTimeout(). Timeout Detenido");}
        }
    },
    stopLoad: function () {
        if (this.loading) {
            $(this.loadingTarget).stopWaiting();
            this.loading = false;
            this.loadingTarget = '';
        }
    },
    stopLoadText: function () {
        try {
            $(this.idLoadText).fade({
                duration: 0.5
            });
        } catch (e) {
            if (this.debug) {
                console.log('PrivaliaCoreUI.stopLoadText (' + this.errId + '): ', e);
            }
        }
    },
    htmlSetExtraImg: function () {
        $$('.' + this.cssJson + '_img').each(function (item) {
            pathImg = $(item).title;
            if (pathImg != '') {
                $(item).src = pathImg;
                $(item).title = '';
            }
        }, this);
    },
   htmlSetExtraLinks: function () {
        $$('.' + this.cssJson + '_link').each(function (item) {
            href = $(item).title;
            if (href != '') {
                $(item).href = href;
                $(item).title = '';
            }
        }, this);
    },
    htmlPushBuilt: function (s_mode) {
        var target = this.getTarget();
        var data = this.getBuilt();
	 //if (this.debug) console.log("Target:"+target+"->"+data);
        if (data != '' && target != '') {
            switch (s_mode) {
            case 'add':
                $(target).insert({
                    bottom: data
                });
                break;
            case 'push':
            default:
                $(target).update(this.built);
            }
            this.setAsJsoned(target);
        }
    },
    htmlGenerate: function (options) {
        var html = '';
        this.resetBuilt();
	if (this.debug) console.log("Generando html, targets a modificar:"+this.numTargets);
        if (this.numTargets > 0) {
		
            var options = Object.extend({
                pushData: this.addBuilt,
                mode: 'push'
            }, arguments[0] || {});
            this.Data.each(function (oData) {
                var target = oData.target;
                var html = oData.html;
		
                if (!html.empty()) {
                    this.setTarget(target);
		    if (this.debug) console.log("Target Actual:" + target);
                    var tpl = new Template(html);
                    this.setTpl(tpl);
		    
                    if (Object.isArray(oData.json)) {
                        vDataToPush = oData.json;
                    } else {
                        vDataToPush = [oData.json];
                    }
			//console.log("Datos a enviar"+ oData.json+ ":"+vDataToPush);
                    vDataToPush.each(options.pushData.bind(this));
                    this.htmlPushBuilt(options.mode);
                    this.resetBuilt();
                }
                html = '';
            }, this);
        }
    },
    htmlShowJson: function () {
        $$('.' + this.cssJsoned).each(function (item) {
            new Effect.Appear(item, {
                duration: this.duration_show
            });
        }, this);
        $$('.' + this.cssJson).each(function (item) {
            $(item).update(' ');
            new Effect.Appear(item, {
                duration: this.duration_show
            });
        }, this);
    },
    htmlInit: function () {
        if (this.debug) console.log('_init(): Iniciamos el volcado de datos');
        
            try {

                this.buildPage(this.getBuild());

            } catch (e) {
                
                    console.log(e, 'CestaVipMain.getData._init.buildPage@' + this.idClass);
               
            }
        
        if (!this.error) {
	    this.stopLoad();
            this.htmlShowJson();
	    this.htmlSetExtraImg();
	    this.htmlSetExtraLinks();
            /*this.setTooltips(this.getBuild());
            this.setExtraInputs();
            
            
           
            */
        }
    },
    ajaxPreInit: function (target) {
        
	if (this.showLoad) {
            if (Object.isUndefined(target)) {
                target = 'page';
            }
            if (this.debug) console.log('ajaxPreInit(): Pre-Inicializando antes de realizar la carga de datos, target:'+target);
	    if (!this.loading) {
		        this.loadingTarget = target;
		        if (!Prototype.Browser.IE) {
		            $(this.loadingTarget).startWaiting();
		        }
		        this.loading = true;
		    
	    }
	}
    },
    ajaxFail: function (status) {
			
		this.load();
		document.location.href = urlRedir[status];
				
		if (this.debug) 
			console.log('header response', status);
		
		this.stopLoad();
    },
    ajaxSet: function (target, json) {
        var html = '';
        if (target != "") {
            
                try {
		    //alert(target);
                    html = $(target).innerHTML;
                } catch (e) {
                    if (this.debug) console.log(e, 'CestaVipMain.ajaxGetData.ajaxCallData.ajaxResponse._set@' + this.idClass + '[' + target + ']');    
                }
                this.Data[this.numTargets] = {
                    id: this.numTargets,
                    html: html,
                    json: json,
                    target: target
                };
            	this.numTargets++;
        }
    },
    ajaxNoItems: function(target) {
		if($(target)) {
			notarget = "no_" + target;
			try {
				if($(notarget).hasClassName('hidden')) {
					$(notarget).removeClassName('hidden');
				}
				this.show(notarget);
			}
			catch(e){
				 if (this.debug) console.log(e, 'CestaVipMain.ajaxGetData.ajaxCallData.ajaxResponse.showNoItems@' + this.idClass + '[' + target + ']'); 
			}
		}
	},
     ajaxSetData: function () {
        if (!Object.isArray(this.getAjaxData())) {
            var h = new Hash(this.getAjaxData());
            h.each(function (item) {
                target = item[0];
                values = item[1];
                if (Object.isArray(values)) {
                    this.ajaxSet(target, values);
                    if (values.size() === 0) {
                        this.showNoItems(target);
                    }
                }else {
                    this.ajaxSet(target, values);
                    if (!values) {
                        try 
			{
                               
			    this.ajaxNoItems(target);

                        } catch (e) {
                                
                            console.log(e, 'CestaVipMain.ajaxGetData.ajaxCallData.ajaxResponse.ajaxSetData@' + this.idClass + '. No hay items. Intenta mostrar texto alternativo pero no existe ninguno.');
                                
                        }
                        
                    }
                }
            }, this);
        }
    },
    ajaxParseResponse: function (response) {
        var Res = new Hash(response.responseText.evalJSON());
        this.ajaxData = Res.get("data");
        this.ajaxStatus = Res.get("status");
    },
    ajaxResponse: function (response) {
	this.stopTimeout();
        if (response !== undefined) {
            this.ajaxParseResponse(response);
        }
        if (this.getStatus()) {	//status=OK
               
            try {

                this.ajaxSetData();	//generar array vData

            } catch (e) {
               
                console.log(e, 'CestaVipMain.ajaxGetData.ajaxCallData.ajaxResponse.ajaxSetData@' + this.idClass);
                
            }
      
            if(this.debug) console.log('CestaVipMain getData(): obtenemos los datos via AJAX '+ response);
       
            try {

                this.htmlInit();

            } catch (e) {
                
                console.log(e, 'CestaVipMain.getData._callData._responseCallData._init@' + this.idClass);
                
            }
                
       } else {

                this.error = true;
                this.stopLoad();    
       } 
       
    },
    ajaxCallData: function () {
        var params;
        if (this.urlGetData != '') {
	
            params = {
                onFailure: (function (response) {
                    if (this.debug) { console.log('Error onFailure ' + response.status); }
                    this.ajaxFail(response.status);
                }).bind(this),
                onException: (function (response, error) {
                    if (this.debug) {
                        this.stopLoad();
                        //this._showJson();
                        console.log('CestaVipMain.getData._callData.onException@' + this.idClass + ': ' + error); 
                    }
                }).bind(this),
                onComplete: this.ajaxResponse.bind(this)
            };
	    if(this.debug)console.log("Loading _callData():"+this.urlGetData);	
            new Ajax.Request(this.urlGetData, params);
		
        } else {
            //this._init();
            this.errorMessage('01');
        }
    },
    ajaxGetData: function (urlDataAjax, section) {
	if (this.debug)console.log("CestaVipMain getting data from url: "+ urlDataAjax+" Target section:"+section);
        if (urlDataAjax != "") {
            this.setBuild(section);
	    this.ajaxPreInit();
	    this.setUrlGetData(urlDataAjax);
            this.ajaxCallData();
            this.startTimeout();  
        } else {
            this.errorMessage('01');
        }
    }
});
